package com.xingu.xg.common.service;

import com.xingu.xg.common.AddNodeQuery;
import com.xingu.xg.common.CopyNodeQuery;
import com.xingu.xg.common.DeleteNodeQuery;
import com.xingu.xg.common.entity.TreeNode;
import com.xingu.xg.common.mapper.TreeNodeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class TreeNodeService {

    @Autowired
    private TreeNodeMapper treeNodeMapper;

    // 查询树形结构列表
    public List<TreeNode> listTreeNodes(String parentId) {
        List<TreeNode> nodes = treeNodeMapper.findByParentId(parentId);
        return nodes.stream()
                .peek(node -> node.setChildren(listTreeNodes(node.getId())))
                .sorted(Comparator.comparingInt(TreeNode::getSortOrder))
                .collect(Collectors.toList());
    }

    // 同级创建节点（向上/向下）
    @Transactional
    public TreeNode createSiblingNode(AddNodeQuery param, String nodeName, String operationType) {
        TreeNode selectedNode = treeNodeMapper.findById(param.getSelectedId());
        if (selectedNode == null) throw new IllegalArgumentException("选中节点不存在");

        String parentId = selectedNode.getParentId();
        int level = selectedNode.getNodeLevel();

        TreeNode newNode = new TreeNode();
        newNode.setId(UUID.randomUUID().toString());
        newNode.setParentId(parentId);
        newNode.setNodeName(nodeName);
        newNode.setNodeLevel(level);
        newNode.setCreateTime(new Date());

        List<TreeNode> siblings = treeNodeMapper.findByParentId(parentId);
        int insertPos = siblings.indexOf(selectedNode);

        if ("after".equals(operationType)) insertPos++;
        treeNodeMapper.updateSortOrder(parentId, insertPos, 1);
        newNode.setSortOrder(insertPos + 1);

        if (parentId == null) {
            newNode.setPath("/" + newNode.getId() + "/");
        } else {
            TreeNode parentNode = treeNodeMapper.findById(parentId);
            newNode.setPath(parentNode.getPath() + newNode.getId() + "/");
        }

        treeNodeMapper.insert(newNode);
        return newNode;
    }

    // 创建父级/子级节点
    @Transactional
    public TreeNode createParentChildNode(AddNodeQuery param, String nodeName, String operationType) {
        TreeNode selectedNode = treeNodeMapper.findById(param.getSelectedId());
        if (selectedNode == null) throw new IllegalArgumentException("选中节点不存在");

        TreeNode newNode = new TreeNode();
        newNode.setId(UUID.randomUUID().toString());
        newNode.setNodeName(nodeName);
        newNode.setCreateTime(new Date());

        if ("parent".equals(operationType)) {
            String originalParentId = selectedNode.getParentId();
            newNode.setParentId(originalParentId);
            newNode.setNodeLevel(selectedNode.getNodeLevel() - 1);
            newNode.setSortOrder(selectedNode.getSortOrder());

            if (originalParentId == null) {
                newNode.setPath("/" + newNode.getId() + "/");
            } else {
                TreeNode parentNode = treeNodeMapper.findById(originalParentId);
                newNode.setPath(parentNode.getPath() + newNode.getId() + "/");
            }

            selectedNode.setParentId(newNode.getId());
            selectedNode.setNodeLevel(selectedNode.getNodeLevel() + 1);
            selectedNode.setPath(newNode.getPath() + selectedNode.getId() + "/");
            treeNodeMapper.update(selectedNode);
            updateChildrenPath(selectedNode.getId(), selectedNode.getPath());
        } else {
            newNode.setParentId(param.getSelectedId());
            newNode.setNodeLevel(selectedNode.getNodeLevel() + 1);

            List<TreeNode> children = treeNodeMapper.findByParentId(param.getSelectedId());
            newNode.setSortOrder(children.size() + 1);
            newNode.setPath(selectedNode.getPath() + newNode.getId() + "/");
        }

        treeNodeMapper.insert(newNode);
        return newNode;
    }

    // 复制粘贴节点（保持层级）
    @Transactional
    public List<TreeNode> copyPasteNodes(CopyNodeQuery param, String targetId) {
        TreeNode targetNode = treeNodeMapper.findById(targetId);
        if (targetNode == null) throw new IllegalArgumentException("目标节点不存在");

        Map<String, String> idMapping = new HashMap<>();
        List<TreeNode> result = new ArrayList<>();

        for (CopyNodeQuery.NodeInfo nodeInfo : param.getNodes()) {
            TreeNode copiedNode = copyNodeRecursively(nodeInfo, targetNode, idMapping);
            result.add(copiedNode);
        }

        return result;
    }

    private TreeNode copyNodeRecursively(CopyNodeQuery.NodeInfo nodeInfo,
                                         TreeNode parentNode, Map<String, String> idMapping) {
        if (nodeInfo == null) {
            return null;
        }
        TreeNode newNode = new TreeNode();
        newNode.setId(UUID.randomUUID().toString());
        newNode.setParentId(parentNode.getId());
        newNode.setNodeName(nodeInfo.getNodeName());
        newNode.setNodeType(nodeInfo.getNodeType());
        newNode.setNodeLevel(parentNode.getNodeLevel() + 1);
        newNode.setQuantity(nodeInfo.getQuantity());
        newNode.setUnit(nodeInfo.getUnit());
        newNode.setCreateTime(new Date());

        List<TreeNode> siblings = treeNodeMapper.findByParentId(parentNode.getId());
        newNode.setSortOrder(siblings.size() + 1);
        newNode.setPath(parentNode.getPath() + newNode.getId() + "/");
        treeNodeMapper.insert(newNode);

        idMapping.put(nodeInfo.getOriginalId(), newNode.getId());

        if (nodeInfo.getChildren() != null) {
            for (CopyNodeQuery.NodeInfo childInfo : nodeInfo.getChildren()) {
                if (childInfo != null) {  // 新增子节点空值过滤
                    copyNodeRecursively(childInfo, newNode, idMapping);
                }
            }
        }

        return newNode;
    }

    // 删除节点
    @Transactional
    public void deleteNodes(DeleteNodeQuery param) {
        for (String nodeId : param.getDeleteList()) {
            TreeNode node = treeNodeMapper.findById(nodeId);
            if (node == null) throw new IllegalArgumentException("删除节点不存在");

            treeNodeMapper.deleteByPath(node.getPath());
            updateSortOrderAfterDeletion(node.getParentId(), node.getSortOrder());
        }
    }

    // 辅助方法：更新子节点路径
    private void updateChildrenPath(String parentId, String newParentPath) {
        List<TreeNode> children = treeNodeMapper.findByParentId(parentId);
        for (TreeNode child : children) {
            String newPath = newParentPath + child.getId() + "/";
            child.setPath(newPath);
            treeNodeMapper.update(child);
            updateChildrenPath(child.getId(), newPath);
        }
    }

    // 辅助方法：更新排序
    private void updateSortOrderAfterDeletion(String parentId, int deletedSortOrder) {
        if (parentId == null) return;

        treeNodeMapper.updateSortOrder(parentId, deletedSortOrder, -1);
    }
}